package com.gopay.scheduler.job;

import com.gopay.common.constants.dic.GopayGlobalVariablesConstant;
import com.gopay.common.constants.trans.PgStatus;
import com.gopay.common.dss.tools.FuseTool;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.scheduler.GopayBaseJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZHAOJT on 2017/10/12.
 *
 * 网关状态表检测报警任务
 *
 * 距离当前时间前timeSpan 毫秒的数据，如果大于阈值 则触发报警。
 */
public class PgGenStateDtlCheckJob extends GopayBaseJob {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "fuseTool")
    private FuseTool fuseTool;


    private static final int maxFuseTimes = 1;

    private int threshold; //报警阈值

    private long timeSpan; //时间间隔  单位：毫秒

    @Override
    protected void doJobInternal() {

        try {
            logger.info("执行网关状态表检测报警任务...");

            int count = executeQuery();

            logger.info("timeSpan = " + timeSpan + ", threshold = " + threshold + ", queryCount = " + count);

            if (count > threshold) {
                logger.error("触发阈值执行报警...");
                fuseTool.fuse(GopayGlobalVariablesConstant.PG_STA_CHECK_WARN_SWITCH, GopayGlobalVariablesConstant.PG_STA_CHECK_WARN_MOBILE, maxFuseTimes);
            }

            logger.info("网关状态表检测报警任务结束");

        }catch (Exception e){
            logger.error("网关状态表检测报警任务异常", e);
        }
    }


    private int executeQuery(){
        Date date = new Date(System.currentTimeMillis() - timeSpan);
        Date dateStart = new Date(date.getTime() - (60 * 60 * 1000) );

        StringBuilder sql = new StringBuilder();

        sql.append(" select count(*) from pg_gen_order_status_dtl t");
        sql.append(" where t.status = :status");
        sql.append(" and t.created_ts <= :date");
        sql.append(" and t.created_ts >= :dateStart");

        Map<String, Object> param = new HashMap<>();
        param.put("date", date);
        param.put("dateStart", dateStart);
        param.put("status", PgStatus.INIT.value);

        int count = commonQueryDAO.findCountBySql(sql.toString(), param);


        return count;
    }

    public int getThreshold() {
        return threshold;
    }

    public void setThreshold(int threshold) {
        this.threshold = threshold;
    }

    public long getTimeSpan() {
        return timeSpan;
    }

    public void setTimeSpan(long timeSpan) {
        this.timeSpan = timeSpan;
    }
}
